package lew.bing.gwalo.semaphoreLimiter;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;

/**
 * Created by 刘国兵 on 2018/7/8.
 */
public abstract class DefaultPermits implements Permits {

    // 可以动态修改的map
    public static Map<String,BingoSemaphore> map = new ConcurrentHashMap<>();


    @Override
    public synchronized Semaphore takePermits(String group, String key, int defaultPermits) {
        BingoSemaphore semaphore;
        if (map.containsKey(group+":"+key)) {
            semaphore = map.get(group+":"+key);
        } else {
            semaphore = new BingoSemaphore(defaultPermits);
            map.put(group+":"+key,semaphore);
        }
        if (semaphore.getPermits() <= 0) {
            throw new IllegalArgumentException("此功能已无法使用");
        }
        return semaphore;
    }

    public void changePermits(String key,int permits) {
        if (map.containsKey(key)) {
            BingoSemaphore semaphore = map.get(key);
            semaphore.rebasePermit(permits);
        } else {
            BingoSemaphore semaphore = new BingoSemaphore(permits);
            map.put(key,semaphore);
        }
    }

    public abstract Map<String,Integer> permitsMap();

    @Override
    public synchronized void changePermits() {
        if (permitsMap() != null) {
            for (String key: permitsMap().keySet()) {
                changePermits(key,permitsMap().get(key));
            }
        }
    }

    @Override
    public synchronized void changePermits(String key) {
        if (permitsMap() != null && permitsMap().containsKey(key)) {
            changePermits(key,permitsMap().get(key));
        }
    }
}
